package com.zt.aspect;

import com.zt.mapper.OperateLogMapper;
import com.zt.pojo.OperateLog;
import com.zt.pojo.Result;
import com.zt.utils.CurrentHolder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
public class RecordLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.zt.anno.LogOperation)")
    public Object recordLog(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = null;
        boolean success = true;
        String errorMessage = null;

        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            success = false;
            errorMessage = e.getMessage();
            throw e; // 继续抛出异常，让全局异常处理器处理
        } finally {
            long end = System.currentTimeMillis();
            OperateLog operateLog = OperateLog.builder()
                    .operateEmpId(CurrentHolder.getCurrentId())
                    .operateTime(LocalDateTime.now())
                    .className(pjp.getTarget().getClass().getName())
                    .methodName(pjp.getSignature().getName())
                    .methodParams(Arrays.toString(pjp.getArgs()))
                    .returnValue(success ? result.toString() : Result.error(errorMessage).toString())
                    .costTime(end - start)
                    .build();
            operateLogMapper.insert(operateLog);
        }
        return result;
    }
}
